package com.foxmail.aroundme.youtubedemo.recyclerview;

import android.app.FragmentManager;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.foxmail.aroundme.youtubedemo.utils.Config;
import com.foxmail.aroundme.youtubedemo.R;
import com.foxmail.aroundme.youtubedemo.VideoFragment;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;

import java.util.List;

/**
 * Created by gzl on 2016/10/19.
 */

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
    private List<String> list;
    private Context context;
    private RecyclerViewHolder currentHolder = null;
    private FragmentManager fragmentManager;
    private VideoFragment videoFragment;

    public RecyclerViewAdapter(Context context, List<String> list, FragmentManager fragmentManager) {
        this.context = context;
        this.list = list;
        this.fragmentManager = fragmentManager;
        videoFragment = VideoFragment.getInstance();
    }

    @Override
    public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.item, parent, false);

        RecyclerViewHolder viewHolder = new RecyclerViewHolder(view);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final RecyclerViewHolder holder, final int position) {


        (holder.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                holder.lastViewHolder = currentHolder;
                currentHolder = holder;
                if (holder.lastViewHolder != null) {
                    setViewHide(holder.lastViewHolder);
                }

                setViewShow(holder);

                fragmentManager.beginTransaction().remove(videoFragment).commitAllowingStateLoss();
                fragmentManager.executePendingTransactions();

                fragmentManager.beginTransaction().add(holder.getId(), videoFragment).commitAllowingStateLoss();
                videoFragment.play(list.get(position));

            }
        });
    }

    private void setViewHide(RecyclerViewHolder holder) {
        holder.button.setVisibility(View.VISIBLE);
        holder.changeFrame.setVisibility(View.VISIBLE);
        holder.videoFrame.setVisibility(View.GONE);
        Log.d("msg", "setViewHide");
    }

    private void setViewShow(RecyclerViewHolder holder) {
        holder.button.setVisibility(View.GONE);
        holder.changeFrame.setVisibility(View.GONE);
        holder.videoFrame.setVisibility(View.VISIBLE);
        Log.d("msg", "setViewShow");
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}
